package controller;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class TirazhController {

	public void generateTirazh(File fileToWrite) throws Exception {
		fileToWrite.createNewFile();
		FileWriter fWriter = new FileWriter(fileToWrite);

		Connection conn = DatabaseConnection.getInstance().getConnection();
		Statement st = conn.createStatement();
		ResultSet rs = st
				.executeQuery("SELECT * FROM feed WHERE active=1 ORDER BY date");

		int i = 0;
		int tempRepeat = 0;
		while (rs.next()) {
			i++;
			fWriter.write("№: ".concat(Integer.toString(i)).concat("\r\n"));
			fWriter.write("Дата подачи: ".concat(" ")
					.concat(rs.getString("date")).concat("\r\n"));
			fWriter.write("Количетсво символов: ".concat(" ")
					.concat(rs.getString("simbol_sum")).concat("\r\n"));
			fWriter.write("Количество дублирований в тираже: ".concat(" ")
					.concat(rs.getString("dubl")).concat("\r\n"));
			fWriter.write("Текст объявления: ".concat("\r\n ")
					.concat(rs.getString("feed_text")).concat("\r\n\r\n"));
			tempRepeat = rs.getInt("rep");
			tempRepeat--;
			if (tempRepeat == 0) {
				PreparedStatement ps = conn.prepareStatement(String.format(
						"UPDATE feed SET rep=0, active=0 WHERE id_feed=%s",
						rs.getString("id_feed")));
				ps.executeUpdate();
			} else {
				PreparedStatement ps = conn.prepareStatement(String.format(
						"UPDATE feed SET rep=%s WHERE id_feed=%s", tempRepeat,
						rs.getString("id_feed")));
				ps.executeUpdate();
			}

			if (i >= 500)
				break;

		}
		rs.close();
		st.close();
		fWriter.close();
	}
}
